package com.part2.action.function;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ajaxanywhere.AAUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.part2.Constants;
import com.part2.action.common.CommonAction;
import com.part2.action.common.Config;
import com.part2.action.common.Encode;
import com.part2.action.common.RandomGUID;
import com.part2.action.common.ToHTML;
import com.part2.action.common.form.CustomActionForm;
import com.part2.action.common.form.ValueObject;
import com.part2.action.common.validator.Validator;
import com.part2.beans.Bigclass;
import com.part2.beans.Products;
import com.part2.beans.Smallclass;
import com.part2.business.function.BigClassService;
import com.part2.business.function.ProductsService;
import com.part2.business.function.SmallclassService;
import com.part2.common.query.Page;

public class ProductAction extends CommonAction<Products> {
	private final Log logger = LogFactory.getLog(getClass());
	private SmallclassService smallclassService;
	private static ProductsService productsService;
	private static BigClassService bigClassService;

	private int start = 0;
	private int page_size = 3;
	private int next_page = 0;
	private int _pre_page = 0;
	private int _now_page = 0;

	public void setBigClassService(BigClassService bigClassService) {
		this.bigClassService = bigClassService;
	}

	public void setsmallClassService(SmallclassService smallclassService) {
		this.smallclassService = smallclassService;
	}

	public void setProductsService(ProductsService productsService) {
		this.productsService = productsService;
	}

	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::Products-List");
		String proId = request.getParameter("proId");
		Bigclass bClass = null;
		Page<Products> p = initPage(request, Constants.PRE_PAGE_SIZE);// 设置每页的记录数
		Page<Products> page = productsService.findProducts(p, proId);
		List<Bigclass> bClassList = bigClassService.findBigClass();
		if (Validator.isNotNull(proId))
			bClass = bigClassService.findBigClassByPrimeKey(proId);
		if (page != null) {
			request.setAttribute("page", page);
		} else {
			request.setAttribute("res", "暂无记录！");
		}
		request.setAttribute("bigClassList", bClassList);
		if (bClass != null) {
			request.setAttribute("nowType", bClass.getBclassName());
			request.setAttribute("proId", proId);
		}
		if (AAUtils.isAjaxRequest(request)) {
			AAUtils.addZonesToRefresh(request, "proList");
		}
		logger.info("::::::::::Products-List End");
		return mapping.findForward("productList");
	}
	public ActionForward proList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::Products-List");
		String proId = request.getParameter("proId");
		Bigclass bClass = null;
		Page<Products> p = initPage(request, 3);// 设置每页的记录数
		Page<Products> page = productsService.findProducts(p, proId);
		List<Bigclass> bClassList = bigClassService.findBigClass();
		if (Validator.isNotNull(proId))
			bClass = bigClassService.findBigClassByPrimeKey(proId);
		if (page != null) {
			request.setAttribute("page", page);
		} else {
			request.setAttribute("res", "暂无记录！");
		}
		setClassList(request);
		if (bClass != null) {
			request.setAttribute("nowType", bClass.getBclassName());
			request.setAttribute("proId", proId);
		}
		if (AAUtils.isAjaxRequest(request)) {
			AAUtils.addZonesToRefresh(request, "proList");
		}
		logger.info("::::::::::Products-List End");
		return mapping.findForward("list");
	}

	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::Products-Search");
		ValueObject search = ((CustomActionForm) form).getVoa().getValue(
				"Search");
		String s = search.getField("key");
		if (Validator.isNull(s))
			s = request.getParameter("key");
		Page<Products> p = initPage(request, Constants.PRE_PAGE_SIZE);
		Page<Products> page = productsService.findProductsBySearch(p, s);
		if (page != null) {
			request.setAttribute("page", page);
			request.setAttribute("key", s);
		} else {
			if (Validator.isNotNull(s))
				request.setAttribute("res", "暂无关于" + s + "的记录！");
			else
				request.setAttribute("res", "请输入关键字！");
		}
		if (AAUtils.isAjaxRequest(request)) {
			AAUtils.addZonesToRefresh(request, "proList");
		}
		List<Bigclass> bClassList = bigClassService.findBigClass();
		request.setAttribute("bigClassList", bClassList);
		logger.info("::::::::::Products-Search End");
		return mapping.findForward("productList");
	}

	public ActionForward preAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.setClassList(request);
		return mapping.findForward("productAdd");
	}

	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::Products-Add");
		ValueObject pVo = ((CustomActionForm) form).getVoa().getValue("pro");
		String id = new RandomGUID() + "-pro";
		String title = pVo.getField("title");
		String titleEn = pVo.getField("titleEn");
		String pic = pVo.getField("pic");
		String bigClass = pVo.getField("big");
		String smallClass = pVo.getField("small");
		String type = pVo.getField("type");
		String info = pVo.getField("info");
		String infoEn = pVo.getField("infoEn");
		String content = pVo.getField("content");
		String contentEn = pVo.getField("contentEn");
		String att = pVo.getField("att");

		String root = request.getSession().getServletContext().getRealPath("/");
		String filePath = root + Constants.PRO_HTML_PATH;
		String url = Constants.PRO_URL;

		Products pro = new Products();
		pro.setProductId(id);
		pro.setProductName(title);
		pro.setProductNameEn(titleEn);
		pro.setProductPic(pic);
		pro.setProductInfo(info);
		pro.setProductInfoEn(infoEn);
		pro.setProductContent(content);
		pro.setProductContentEn(contentEn);
		pro.setAttachmentDir(att);
		pro.setBclassId(bigClass);
		pro.setSclassId(smallClass);
		pro.setType(type);
		pro.setCreateDate(new Date());
		pro.setLastModifielDate(new Date());

		productsService.addProducts(pro);
//		ToHTML.makeHTML(filePath, id, url + id, null);
		logger.info("::::::::::Products-Add End");
		return list(mapping, form, request, response);
	}

	public ActionForward preEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.setClassList(request);
		ValueObject pVo = ((CustomActionForm) form).getVoa().getValue("pro");
		String id = request.getParameter("id");
		if (Validator.isNotNull(id)) {
			Products pro = productsService.findProductsByPrimeKey(id);
			if (Validator.isNotNull(pro.getBclassId())) {
				Bigclass bClass = bigClassService.findBigClassByPrimeKey(pro
						.getBclassId());
				if (bClass != null)
					request.setAttribute("bName", bClass.getBclassName());
			}
			if (Validator.isNotNull(pro.getSclassId())) {
				Smallclass sClass = smallclassService
						.findSmallclassByPrimeKey(pro.getSclassId());
				if (sClass != null)
					request.setAttribute("sName", sClass.getSclassName());
			}
			if (pro != null) {
				pVo.setField("id", id);
				pVo.setField("title", pro.getProductName());
				pVo.setField("titleEn", pro.getProductNameEn());
				pVo.setField("pic", pro.getProductPic());
				pVo.setField("type", pro.getType());
				pVo.setField("info", pro.getProductInfo());
				pVo.setField("infoEn", pro.getProductInfoEn());
				pVo.setField("content", pro.getProductContent());
				pVo.setField("contentEn", pro.getProductContentEn());
				pVo.setField("att", pro.getAttachment());
				return mapping.findForward("productEdit");
			}
		}
		System.out.println(">>>>id empty<<<<<");
		return null;
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::Products-Edit");
		ValueObject pVo = ((CustomActionForm) form).getVoa().getValue("pro");
		String id = pVo.getField("id");
		if (Validator.isNotNull(id)) {
			Products pro = productsService.findProductsByPrimeKey(id);
			if (pro != null) {
				String root = request.getSession().getServletContext()
						.getRealPath("/");
				String filePath = root + Constants.PRO_HTML_PATH;
				String url = Constants.PRO_URL;
				
				pro.setProductName(pVo.getField("title"));
				pro.setProductNameEn(pVo.getField("titleEn"));
				pro.setProductPic(pVo.getField("pic"));
				if (Validator.isNotNull(pVo.getField("small")))
					pro.setSclassId(pVo.getField("small"));
				if (Validator.isNotNull(pVo.getField("big")))
					pro.setBclassId(pVo.getField("big"));
				pro.setType(pVo.getField("type"));
				pro.setProductInfo(pVo.getField("info"));
				pro.setProductInfoEn(pVo.getField("infoEn"));
				pro.setProductContent(pVo.getField("content"));
				pro.setProductContentEn(pVo.getField("contentEn"));
				pro.setAttachment(pVo.getField("att"));
				pro.setLastModifielDate(new Date());
				productsService.updateProducts(pro);
//				ToHTML.makeHTML(filePath, id, url + id, null);
			}

		}
		logger.info("::::::::::Products-Edit End");
		return list(mapping, form, request, response);
	}

	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ValueObject pVo = ((CustomActionForm) form).getVoa().getValue("pro");
		String id = request.getParameter("pId");
		String clazzId = request.getParameter("clazz");
		String title = "";
		String content = "";
		String type = "";
		String attchment = "";
		List<Products> proList = null;
		if (Validator.isNotNull(id)) {
			setClassList(request);
			Products p = productsService.findProductsByPrimeKey(id);
			if (p != null) {
				title = p.getProductName();
				content = p.getProductContent();
				type = p.getType();
				attchment = p.getAttachment();
				pVo.setField("title", title);
				pVo.setField("content", content);
				pVo.setField("type", type);
				if (Validator.isNotNull(attchment)) {
					request.setAttribute("attchment", attchment);
				}
				return mapping.findForward("show");
			}
//		} else {
//			if (Validator.isNotNull(request.getParameter("start")))
//				start = Integer.parseInt(request.getParameter("start"));
//			if (Validator.isNotNull(clazzId)) {
//				proList = productsService.findProductsByBigClass(clazzId);
//			} else
//				proList = productsService.findProducts();
//			if (proList != null && proList.size() > 0) {
//				request.setAttribute("proList", proList);
//				request.setAttribute("start", new Integer(start));
//				request.setAttribute("page", new Integer(page_size));
//				int previous = start - page_size;
//				if (previous >= 0) {
//					request.setAttribute("preHtml", "list_" + _pre_page
//							+ ".html");
//					request.setAttribute("previous", new Integer(previous));
//				}
//				// if there is a next page, set the next variable
//				int next = start + page_size;
//				if (next < proList.size()) {
//					request.setAttribute("nextHtml", "list_" + next_page
//							+ ".html");
//					request.setAttribute("next", new Integer(next));
//				}
//				setClassList(request);
//				return mapping.findForward("list");
//			}
		}
		return null;
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("::::::::::Products-Delete");
		String id = request.getParameter("id");
		if (Validator.isNotNull(id)) {
			productsService.deleteProducts(id);
			logger.info("::::::::::delete " + id + " success");
			return this.list(mapping, form, request, response);
		}
		logger.info("::::::::::Products-Delete End");
		return null;
	}

	// public ActionForward makeHtmlList(ActionMapping mapping, ActionForm form,
	// HttpServletRequest request, HttpServletResponse response)
	// throws Exception {
	// List proList = productsService.findProducts();
	// Iterator it = proList.iterator();
	// String id = "";
	// String root = request.getSession().getServletContext().getRealPath("/");
	// String webPath = request.getContextPath();
	// String filePath = root + Constants.PRO_HTML_PATH;
	// String url = Config.readValue("webSite")+Constants.PRO_URL;
	// String href_url = "";
	// boolean listFlag = false;// 判断是否需要生成列表
	// if (proList != null && proList.size() > 0) {
	// response.setContentType("text/html;charset=UTF-8");
	// response.getWriter().write("产品内页开始<br>");
	// while (it.hasNext()) {
	// logger.info("has next...");
	// Products pro = (Products) it.next();
	// id = pro.getProductId();
	// ToHTML.makeHTML(filePath, id, url + id, null);
	// listFlag = true;// 完成所有页面的生成后开始生成列表
	// href_url = webPath + Constants.PRO_HTML_PATH
	// + Encode.encodeByMD5(id) + ".html";
	// response.getWriter().write(
	// "<a href='" + href_url + "' target='_blank'>"
	// + pro.getProductName() + "</a>" + "已生成!<br>");
	// logger.info(":::::::::::::::make HTML finsh!:::::::::::::");
	// }
	// if (listFlag) {
	// response.getWriter().write("产品列表开始<br>");
	// int count = proList.size() / page_size;
	// url = Config.readValue("webSite")+Constants.PRO_LIST_URL;
	// if (proList.size() % page_size > 0)
	// count++;
	// for (int i = 1; i <= count; i++) {
	// _now_page = i;
	// _pre_page = _now_page;
	// next_page = _now_page;
	// if (i == 1)
	// next_page = _now_page;
	// if (i > 1)
	// --_pre_page;
	// if (i > 0 && i != count)
	// ++next_page;
	// // 参数i用来保证每一页都是唯一的
	// ToHTML.makeHTML(filePath, "list_" + i, url + start + "&i="
	// + new RandomGUID(), "list");
	// // 全局变量start
	// start += page_size;
	// href_url = webPath + Constants.PRO_HTML_PATH + "list_" + i
	// + ".html";
	// response.getWriter().write(
	// "<a href='" + href_url + "' target='_blank'>list_"
	// + i + "</a>" + "已生成!<br>");
	// logger
	// .info(":::::::::::::::make HTML List finsh!:::::::::::::");
	// }
	// listFlag = false;// 将列表状态恢复为false
	// }
	// if (!listFlag) {
	// start = 0;// 完成列表后必须归零
	// _now_page = 0;
	// _pre_page = 0;
	// next_page = 0;
	// href_url = null;
	// }
	// }
	// return null;
	// }

	public void setClassList(HttpServletRequest request) {
		List<Bigclass> bClassList = bigClassService.findBigClass();
		List<Smallclass> sClassList = smallclassService.findSmallclass();
		if (bClassList != null & sClassList != null) {
			request.setAttribute("blist", bClassList);
			request.setAttribute("slist", sClassList);
		}
	}

}
